package com.order.api.service.impl;


import com.order.api.constant.BaseException;
import com.order.api.constant.MsgEnum;
import com.order.api.dao.UsersDao;
import com.order.api.po.Users;
import com.order.api.po.UsersExample;
import com.order.api.service.AdminUserService;
import com.order.api.service.TokenService;
import com.order.api.util.SafeHashGenerator;
import com.order.api.util.ThreadLocalUtil;
import com.order.api.vo.TokenModel;
import com.order.api.vo.request.PwdChangeRequest;
import com.order.api.vo.request.UserFindRequest;
import com.order.api.vo.request.UserLoginRequest;
import com.order.api.vo.request.UserSaveRequest;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;


import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ThreadLocalUtil threadLocalUtil;

    /**
     * 是否开启默认初始密码
     */
    @Value("${user-settings.isDefaultPwd}")
    private boolean isDefaultPwd;

    /**
     * 默认初始密码
     */
    @Value("${user-settings.defaultPwd}")
    private String defaultPwd;

    /**
     * admin手机号
     */
    private String ADMIN_PHONE = "admin";


    @Override
    public String adminUserLogin(UserLoginRequest request) {
        //参数判断
        if (StringUtils.isEmpty(request.getPhone())){
            throw  new BaseException(MsgEnum.ERROR_NOT_PHONE);
        }
        if (StringUtils.isEmpty(request.getPassword())) {
            throw new BaseException(MsgEnum.ERROR_NOT_PASSWORD);
        }
        //查询用户
        Users users = usersDao.findUserByPhone(request.getPhone());
        if (users==null){
            throw new BaseException(MsgEnum.ERROR_NOT_CHECK_USER);
        }
        //验证密码是否正确
        System.out.println(SafeHashGenerator.getStretchedPassword("--------"+request.getPassword(), users.getId().toString()));
        System.out.println("-----------------------"+users.getPassword());
        boolean passwordCorrect = SafeHashGenerator.getStretchedPassword(request.getPassword(), users.getId().toString()).equals(users.getPassword());
        if(!passwordCorrect){
            throw new BaseException(MsgEnum.ERROR_NOT_CHECK_USER);
        }
        //验证密码有效性,暂未写

        //创建token
        TokenModel model = tokenService.createToken(users.getId());
        return model.toString();

    }

    @Override
    public boolean logout() {
        return tokenService.deleteToken(threadLocalUtil.getUserId());
    }

    @Override
    public boolean saveUSer(UserSaveRequest request) {
        //判断参数
        if (StringUtils.isEmpty(request.getName())) {
            throw new BaseException(MsgEnum.ERROR_NOT_USERNAME);
        }
        if (StringUtils.isEmpty(request.getPhone())) {
            throw new BaseException(MsgEnum.ERROR_NOT_PHONE);
        }
        //验证手机是否被使用
        UsersExample example = new UsersExample();
        example.createCriteria().andPhoneEqualTo(request.getPhone());
        List<Users> usersList = usersDao.selectByExample(example);
        if (usersList !=null && usersList.size() > 0 && !usersList.get(0).getId().equals(request.getId())){
            throw new BaseException(MsgEnum.ERROR_LOGINED_PHONE);
        }
        //验证用户名是否已使用
        UsersExample example1 = new UsersExample();
        example1.createCriteria().andNameEqualTo(request.getName());
        List<Users> usersList1 = usersDao.selectByExample(example1);
        if (usersList1 !=null && usersList1.size()>0 && usersList.size() > 0 && !usersList.get(0).getId().equals(request.getId())){
            throw new BaseException(MsgEnum.ERROR_LOGINED_NAME);
        }
        return request.getId() == null ? addUser(request) : updateUser(request);
    }

    private boolean updateUser(UserSaveRequest request) {
        Users users=Users.builder()
                .name(request.getName())
                .age(request.getAge())
                .id(request.getId())
                .phone(request.getPhone())
                .gender(request.getGender())
                .address(request.getAddress())
                .build();
        return usersDao.updateByPrimaryKeySelective(users) ==1;
    }

    private boolean addUser(UserSaveRequest request) {
        //生成初始密码
        String newPassword=getNewPassword();
        //当前时间
        //Date time = Calendar.getInstance().getTime();
        //当前用户
        //Integer userId = threadLocalUtil.getUserId();
        Users users=Users.builder()
                .name(request.getName())
                .phone(request.getPhone())
                .address(request.getAddress())
                .age(request.getAge())

                .gender(request.getGender())
                .build();
        boolean flag = usersDao.insertSelective(users) == 1;
        if (flag){
            Users users1 = new Users();
            users1.setId(users.getId());
            System.out.println(SafeHashGenerator.getStretchedPassword(newPassword,users.getId().toString())+"---------------");
            users1.setPassword(SafeHashGenerator.getStretchedPassword(newPassword,users.getId().toString()));
            usersDao.updateByPrimaryKeySelective(users1);
        }
        return flag;
    }

    @Override
    public boolean resetPassword(UserFindRequest request) {
        boolean flag=true;
        if (request !=null){
            Users users = usersDao.selectByPrimaryKey(request.getId());
            if (users !=null && users.getPhone() !=null){
                boolean isAdmin = ADMIN_PHONE.equals(users.getPhone());
                String newPassword = isAdmin ?ADMIN_PHONE : getNewPassword();
                int count = usersDao.updateByPrimaryKeySelective(Users.builder()
                .id(users.getId())
                .password(SafeHashGenerator.getStretchedPassword(newPassword,users.getId().toString()))
                .build());
                flag = count == 1;
                if (flag){
                    tokenService.deleteToken(request.getId());
                }
            }
        }
        return flag;
    }

    @Override
    public boolean changePassword(PwdChangeRequest request) {
        if (StringUtils.isEmpty(request.getNewPwd())){
            throw new BaseException(MsgEnum.ERROR_NOT_PASSWORD);
        }
        if (StringUtils.isEmpty(request.getResetNewPwd())){
            throw new BaseException(MsgEnum.ERROR_NOT_NEW_PASSWORD);
        }
        Long userId = threadLocalUtil.getUserId();
        int count = usersDao.updateByPrimaryKeySelective(Users.builder()
                .password(SafeHashGenerator.getStretchedPassword(request.getNewPwd(),userId.toString()))
                .id(userId)
                .build());


        if (count == 1){
            tokenService.deleteToken(userId);
        }
        return count == 1;
    }

    private String getNewPassword() {
        String newPassword;
        if (isDefaultPwd && StringUtils.isNotEmpty(defaultPwd)) {
            newPassword = defaultPwd;
        } else {
            newPassword = RandomStringUtils.randomAlphanumeric(10);
        }
        return newPassword;

    }

    @Test
    public void  test(){
        System.out.println(getNewPassword());
        System.out.println(Calendar.getInstance().getTime());
        System.out.println(new Date());
    }

}

